#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
修复三元运算符和其他高级Python语法
"""
import os
import re
from pathlib import Path


def fix_ternary_operators(file_path):
    """修复三元运算符"""
    print(f"检查: {file_path}")
    
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    original_content = content
    
    # 修复 {{ var if condition else default }}
    # 转换为 {% if condition %}{{ var }}{% else %}default{% endif %}
    
    # 匹配模式: {{ variable if (condition) else 'default' }}
    pattern = r'{{\s*(\w+(?:\.\w+)*)\s+if\s+\(([^)]+)\)\s+else\s+[\'"]([^\'"]+)[\'"]\s*}}'
    
    def replace_ternary(match):
        variable = match.group(1)
        condition = match.group(2)
        default = match.group(3)
        
        # 转换条件
        condition = condition.replace(' and ', ' and ')
        
        result = '{% if ' + condition + ' %}{{ ' + variable + ' }}{% else %}' + default + '{% endif %}'
        return result
    
    content = re.sub(pattern, replace_ternary, content)
    
    # 修复更简单的形式 {{ var if var else 'default' }}
    pattern2 = r'{{\s*(\w+(?:\.\w+)*)\s+if\s+(\w+(?:\.\w+)*)\s+else\s+[\'"]([^\'"]+)[\'"]\s*}}'
    
    def replace_simple_ternary(match):
        variable = match.group(1)
        condition = match.group(2)
        default = match.group(3)
        
        result = '{% if ' + condition + ' %}{{ ' + variable + ' }}{% else %}' + default + '{% endif %}'
        return result
    
    content = re.sub(pattern2, replace_simple_ternary, content)
    
    if content != original_content:
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
        print(f"✓ 已修复: {file_path}")
        return True
    else:
        print(f"- 无需修复: {file_path}")
        return False


def fix_all_templates(templates_dir):
    """修复所有模板文件"""
    templates_path = Path(templates_dir)
    
    if not templates_path.exists():
        print(f"错误: 模板目录不存在: {templates_dir}")
        return
    
    html_files = list(templates_path.rglob('*.html'))
    total_files = len(html_files)
    fixed_files = 0
    
    print(f"\n找到 {total_files} 个HTML模板文件")
    print("=" * 60)
    
    for html_file in html_files:
        if fix_ternary_operators(html_file):
            fixed_files += 1
    
    print("=" * 60)
    print(f"\n修复完成!")
    print(f"总文件数: {total_files}")
    print(f"已修复: {fixed_files}")
    print(f"无需修复: {total_files - fixed_files}")


if __name__ == '__main__':
    project_root = Path(__file__).parent
    templates_dir = project_root / 'templates'
    
    print("=" * 60)
    print("Django模板三元运算符修复工具")
    print("=" * 60)
    
    fix_all_templates(templates_dir)
    
    print("\n✅ 所有模板文件已处理完成!")
